import { defineStore } from "pinia";
import { ref, watch } from "vue";

function initData() {
  return {
    loginUserInfo: null,
    menuCodes: [],
  };
}

export const userStore = defineStore("userData", () => {
  const state = ref(initData());
  // 持久化存储
  // 检测
  watch(
    state,
    (newObj) => {
      localStorage.setItem("userState", JSON.stringify(newObj));
    },
    {
      deep: true,
    }
  );

  // 动态添加路由
  function menuRoute(router, type) {
    if (type === "refresh") {
      const userState = JSON.parse(localStorage.getItem("userState"));
      if (userState) {
        state.value = userState;
      } else {
        return;
      }
    }

    const menuList = state.value.loginUserInfo?.menuTrees || [];
    const modules = import.meta.glob("../views/**/*.vue");
    let routeArr = [];
    state.value.routeList = [];
    for (const e of menuList) {
      if (e.children) {
        let children = [];
        for (const c of e.children) {
          let component = `../views/${c.data.component}`;
          children.push({
            name: c.data.name,
            path: c.data.path,
            component: modules[component],
          });
        }
        routeArr.push({
          name: e.data.name,
          path: e.data.path,
          children,
        });
      } else {
        if (e.data.component) {
          let component = `../views/${e.data.component}`;
          routeArr.push({
            name: e.data.name,
            path: e.data.path,
            component: modules[component],
          });
        }
      }
    }
    routeArr.forEach((r) => {
      router.addRoute("main", r);
    });
  }

  function checkPermission(code) {
    let b = false;
    if (state.value.menuCodes.includes(code)) {
      b = true;
    }
    return b;
  }
  return {
    state,
    menuRoute,
    checkPermission,
  };
});
